package role

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"xr-game-server/core/event"
	"xr-game-server/core/httpserver"
	"xr-game-server/core/xrtoken"
	"xr-game-server/dao/roledao"
	"xr-game-server/dao/serverdao"
	"xr-game-server/dto/roledto"
	"xr-game-server/errercode"
	"xr-game-server/gameevent"
	"xr-game-server/module/server"
)

func EnterGame(ctx context.Context, req *roledto.RoleEnterGameReq) (res *roledto.RoleEnterGameRes, err error) {

	accountId := g.RequestFromCtx(ctx).GetHeader(httpserver.AuthId)
	caches := roledao.GetRoleBy(gconv.Uint64(accountId))

	for _, role := range caches {
		if role.ID == req.RoleId {
			serverDB := serverdao.GetServer(role.ServerId)
			if serverDB == nil {
				return nil, errercode.CreateCode(errercode.ServerNotExist)
			}
			if !server.CanEnter(serverDB) {
				return nil, errercode.CreateCode(errercode.ServerNotOpen)
			}
			tokenStr := xrtoken.AddAppToken(req.RoleId)
			//发布角色进入游戏服事件
			event.Pub(gameevent.RoleEnterGameEvent, gameevent.NewRoleEnterGameEventData(
				role.ID, role.ServerId,
			))
			return roledto.NewRoleEnterGameRes(role.ID, tokenStr), nil
		}
	}
	return nil, errercode.CreateCode(errercode.RoleError)
}
